//= require <framework/js/ClassLoader>

instance("framework.bootloader", {
	start : function(){
		var self=this;
		this.configure();
		if(window.boot && (typeof window.boot === "function")){
			if(window.config.autoload) {
				if(NSRegistry[window.config.namespace]) {
					window.boot(window.config, NSRegistry[window.config.namespace]);
				}
				else {
					this.downloadApp(this.appsourcefile(), function(){
						self.configure();
						var applicationClass = NSRegistry[window.config.namespace];
						window.boot(window.config, applicationClass);
					});
				}
			}
			else {
				window.boot(window.config, null);
			}
		}
	},

	configure : function() {
		window.config = js.extend((window.config||{}), (window.appconfig||{}));
		return window.config;
	},

	appsourcefile : function(){
		if (window.config.APPSRC) {
			return window.config.APPSRC;
		}
		else {
			var approot = (window.config.APPROOT) ? window.config.APPROOT : "";
			var ext = (window.config.minified) ? ".min.js" : ".js";
			var cache = (typeof window.config.cache == "boolean")?window.config.cache:false;
			if(browser.DeviceInfo.browser == "Opera" || !cache) {
				ext = ext + "?time=" + new Date().getTime();
			}
			return (approot + "cdn/src/") + window.config.namespace + ext
		}
	},

	downloadApp : function(appsrc, callback) {
		var xhr = new js.ClassLoader();
            xhr.onreadystatechange = function() {
                if(this.readyState == 4) {callback(xhr);}
            };
		    xhr.open("GET", appsrc, true);
			xhr.send();
	}
});
	

function boot(config, Application){
	if(window.config.autoload) {
		var container = (window.config.container) ? 
			Sly.search(window.config.container, document.body)[0] : document.body;
			
		if(!container) {
			alert("Unable to embed js application named: " + window.config.namespace + ". No div container found");
			return;
		}
		window.application = new Application(config); //see appconfig.namespace for Class type
		container.appendChild(window.application.element);
	}
	else {}
};

jQuery(document).ready(function(){ 
	framework.bootloader.start();
});
